const { editQuestion, getQuestionList, addTagSv, getQuestionByQuestionId, getQuestionByContent, createQuestion, destroyQuestionByQuestionId } = require('../service/question.service')
const { noAccess, serverError, repeatedQuestion } = require('../constants/error.type')

const MAX_LIMIT = 200

// 提问
const ask = async (ctx, next) => {
  const { content } = ctx.request.body
  const { id } = ctx.state.userinfo
  try {
    const result = await getQuestionByContent(content)
    if (result) {
      return ctx.app.emit('error', repeatedQuestion, ctx)
    } else {
      await createQuestion({ content, userId: id })
      ctx.body = {
        code: 0,
        message: '发布成功'
      }
    }
  } catch (err) {
    console.error('[ask error]: ', err)
    return ctx.app.emit('error', serverError, ctx)
  }
  await next()
}

// 编辑问题
const editQuestionByQuestionId = async (ctx, next) => {
  const { questionId, content } = ctx.request.body
  try {
    await editQuestion({ questionId, content })
    ctx.body = {
      code: 0,
      message: '编辑成功'
    }
  } catch (err) {
    console.error('[editQuestion error]: ', err)
    return ctx.app.emit('error', serverError, ctx)
  }

  await next()
}

// 给问题添加tag
const addTag = async (ctx, next) => {
  const { questionId, tags } = ctx.request.body
  try {
    const tagToJsonstring = JSON.stringify(tags)
    await addTagSv({ questionId, tags: tagToJsonstring })
    ctx.body = {
      code: 0,
      message: '添加成功'
    }
  } catch (err) {
    console.error('[addTag error]: ', err)
    return ctx.app.emit('error', serverError, ctx)
  }
  await next()
}

// 获取问题列表
const getQuestions = async (ctx, next) => {
  const { page, limit, sortBy, keyword } = ctx.request.query
  try {
    let [questionList, amount] = await getQuestionList({ page: Number(page) || 1, limit: (Number(limit) || MAX_LIMIT), sortBy, keyword })
    questionList.forEach(question => {
      question.set('tags', JSON.parse(question.get('tags') || '[]'))
    })
    ctx.body = {
      code: 0,
      message: '获取成功',
      total: amount,
      data: questionList || []
    }
  } catch (err) {
    console.error('[getQuestions error]: ', err)
    return ctx.app.emit('error', serverError, ctx)
  }

  await next()
}

// 通过问题id 获取某个问题
const getByQuestionId = async (ctx, next) => {
  const { questionId } = ctx.request.query
  try {
    const question = await getQuestionByQuestionId(questionId)
    ctx.body = {
      code: 0,
      message: '获取成功',
      data: question || {}
    }
  } catch (err) {
    console.error('[getQuestionsByQuestionId error]', err)
    return ctx.app.emit('error', serverError, ctx)
  }

  await next()
}

const deleteQuestionByQuestionId = async (ctx, next) => {
  const { questionId } = ctx.request.body
  const { isAdmin } = ctx.state.userinfo
  try {
    if (isAdmin) {
      await destroyQuestionByQuestionId(questionId)
      ctx.body = {
        code: 0,
        message: '删除成功'
      }
    } else {
      return ctx.app.emit('error', noAccess, ctx)
    }
  } catch (err) {
    console.error('[deleteQuestionByQuestionId error]', err)
    return ctx.app.emit('error', serverError, ctx)
  }
  await next()
}

module.exports = {
  ask,
  editQuestionByQuestionId,
  addTag,
  getQuestions,
  getByQuestionId,
  deleteQuestionByQuestionId
}
